package search;

import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: 杰哥
 * Date: 2020/4/11
 * Time: 9:57
 */
public class FibonacciSearch {

    public static int maxSize = 20;
    public static void main(String[] args) {
        int[] arr = {1,8,10,89,1000,1234};
        System.out.println(fibSearch(arr,1234 ));
    }

    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i =2; i < maxSize; i++) {
            f[i] = f[i-1] + f[i-2];
        }
        return f;
    }

    /**
     * 斐波拉契查找算法
     * 非递归方式
     * @param arr
     * @param key 需要查找的关键码
     * @return 返回对应的下标，如果没有返回-1
     */
    public static int fibSearch(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0; //表示斐波拉契分割数值的下标
        int mid = 0;
        int[] f = fib();
        //获取到斐波拉契分割数值的下标(结束循环后 f[k]-1 不再小于high,就是说 f[k]-1 等于数组长度或者大于数组长度)
        while (high > f[k] -1) {
            k++;
        }
        //因为f[k]-1 可能大于 arr 的长度，所有需要使用Arrays类构造一个新的数组(该新数组长度等于f[k]-1)并指向 arr
        int[] temp = Arrays.copyOf(arr, f[k]-1);
        for (int i = high+1; i < temp.length; i++) {
            temp[i] = arr[high]; //用arr数组最后一个值填充新数组后面为0的部分
        }

        while (low <= high) {
            mid = low + f[k-1] -1;
            if(key < temp[mid]) {
                high = mid - 1;
                k--;
            }else if(key > temp[mid]) {
                low = mid + 1;
                k -= 2;
            }else {
                if(mid <= high) {
                    return mid;
                }else {
                    return high;
                }
            }
        }
        return -1;
    }



}
